package ssm.integration.service.impl;

import ssm.integration.mapper.ScheduleMapper;
import ssm.integration.pojo.Schedule;
import ssm.integration.service.ScheduleService;
import ssm.integration.utils.PageBean;
import ssm.integration.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * description: 业务层实现类
 *
 * 1. @Service 类路径扫描标识，添加到IOC容器
 * 2. 实现业务层接口方法
 * 3. 分页插件 PageHelper 进行分页查询，`PageHelper.startPage(currentPage, pageSize);` 会自动在SQL语句执行limit操作。
 * 4. @Autowired 调用Mapper接口执行查询操作，方法实现查询，由分页插件自动做分页处理
 * 5. 分页插件 PageHelper 用 PageInfo 接收查询结果
 * 6. 装配结果模板类 PageBean、R
 */

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Override
    public R page(int pageSize, int currentPage) {
        // 分页查询，调用插件，会自动在SQL语句执行limit操作
        PageHelper.startPage(currentPage, pageSize);
        // 调用Mapper接口执行查询方法，返回所有结果
        List<Schedule> scheduleList = scheduleMapper.queryList();
        // 分页数据装配，调用插件接收
        PageInfo<Schedule> info = new PageInfo<>(scheduleList);

        // 装配结果模板类PageBean
        PageBean<Schedule> pageBean = new PageBean<>(currentPage, pageSize,
                info.getTotal(), info.getList());

        // 装配结果模板类R
        R ok = R.ok(pageBean);
        return ok;
    }

    @Override
    public R remove(Integer id) {
        int rows = scheduleMapper.deleteById(id);
        if (rows > 0){
            return R.ok(null);
        }
        return R.fail(null);
    }

    @Override
    public R save(Schedule schedule) {
        int rows = scheduleMapper.insert(schedule);
        if (rows > 0){
            return R.ok(null);
        }
        return R.fail(null);
    }

    @Override
    public R update(Schedule schedule) {
        //判断id不能为null
        if (schedule.getId() == null) {
            return R.fail("核心参数为null，无法修改！");
        }

        int rows = scheduleMapper.update(schedule);

        if (rows > 0){
            return R.ok(null);
        }
        return R.fail(null);
    }
}
